﻿package edzis.translatebuddy.view.components {
	import edzis.translatebuddy.events.DataProxyEvent;
	import fl.controls.ComboBox;
	import fl.data.DataProvider;
	import fl.events.ComponentEvent;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.ui.Keyboard;
	
	/**
	 * The View Component for adding a word to the translation list
	 * @author Edgars Simsons
	 */
	public class ChoseSession extends ChoseSession_design {
		private var _enterDown	:Boolean;
		private var savedSession		:ComboBox;
		
		public function ChoseSession() {
			visible = false;
		}
		
		public function init(allSessions:DataProvider) :void {
			savedSession = savedSession_mc as ComboBox;
			savedSession_mc.dataProvider = allSessions;
			savedSession_mc.addEventListener(Event.CHANGE, onSessionChange);
			savedSession_mc.addEventListener(Event.CLOSE, onSessionChangeClose);
			
			newSession_txt.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
			newSession_txt.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
			
			startBtn.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
			startBtn.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
			startBtn.addEventListener(MouseEvent.CLICK, onStartNewSession);
		}
		
		private function onSessionChangeClose(e:Event):void {
			if (savedSession_mc.length == 1) {
				addEventListener(Event.ENTER_FRAME, singleSessionSelected);	//	A hack to prevent error from closing the ComboBox from a click outside it
			}
		}
		
		private function singleSessionSelected(e:Event):void {
			removeEventListener(Event.ENTER_FRAME, singleSessionSelected);
			onSessionChange(e);
		}
		
		private function onSessionChange(e:Event):void {
			ArthropodDebug.log("onSessionChange");
			dispatchEvent( new DataProxyEvent(DataProxyEvent.SELECT_SESSION, savedSession.selectedItem.id ));
		}
		
		private function onStartNewSession(e:MouseEvent):void {
			if (newSession_txt.text != "") dispatchEvent( new DataProxyEvent(DataProxyEvent.TRY_CREATE_SESSION, newSession_txt.text));
		}
		
		private function onKeyDown(e:KeyboardEvent):void {
			if (e.keyCode == Keyboard.ENTER && !_enterDown) {
				_enterDown = true;
				onStartNewSession(null);
			}
		}
		
		private function onKeyUp(e:KeyboardEvent):void {
			if (e.keyCode == Keyboard.ENTER) _enterDown = false;
		}
		
	}
	
}